﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

using System.Collections.ObjectModel;

using GPACalculatorCore.Models;


// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238

namespace GPACalculatorForWindowsStoreApp
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPage : Page
    {
        private Button _seletedGradeButton;

        public MainPage()
        {
            this.InitializeComponent();
        }

        public ObservableCollection<Grade> Grades { get; set; }

        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The Parameter
        /// property is typically used to configure the page.</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        #region Grade Button

        private void GradeButton_Tapped(object sender, TappedRoutedEventArgs e)
        {
            Button tappedGradeButton = sender as Button;
            Debug.WriteLine("grade button : {0}", tappedGradeButton.Content);

            ClearButtonBackground(GradeStackPanel);
            tappedGradeButton.Background = new SolidColorBrush(Colors.SkyBlue);
            _seletedGradeButton = tappedGradeButton;
        }

        private void ClearButtonBackground(Panel panel)
        {
            var gradeButtons = GetButtonsInPanel(panel);
            foreach (Button gradeButton in gradeButtons)
            {
                gradeButton.Background = new SolidColorBrush(Colors.Transparent);
            }
        }

        private IEnumerable<Button> GetButtonsInPanel(Panel panel)
        {
            foreach (UIElement element in panel.Children)
            {
                if (element is Button)
                {
                    yield return (element as Button);
                }
                else if (element is Panel)
                {
                    var buttons = GetButtonsInPanel(element as Panel);
                    foreach (Button button in buttons)
                        yield return button;
                }
            }
        }

        #endregion

        #region Credit Button

        private void CreditButton_Tapped(object sender, TappedRoutedEventArgs e)
        {
            Button tappedCreditButton = sender as Button;
            Debug.WriteLine("credit button : {0}", tappedCreditButton.Tag);

            if (_seletedGradeButton != null)
            {
                string gradeString = _seletedGradeButton.Content as string;
                int credit = int.Parse(tappedCreditButton.Tag as string);

                char mainGrade = gradeString[0];
                char subGrade = gradeString[1];


                Grades.Add(new Grade(mainGrade, subGrade, credit));

                ClearButtonBackground(GradeStackPanel);
                _seletedGradeButton = null;

                calculateGPA();

                var ignore = Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                {
                    GradeListView.ScrollIntoView(GradeListView.Items[Grades.Count - 1]);
                });
            }
        }

        private void calculateGPA()
        {
            int totalCredit = Grades.Sum(g => g.Credit);
            float gradePointTotal = Grades.Sum(g => g.GradePoint * g.Credit);
            float gradePointAverage = gradePointTotal / totalCredit;

            GPATextBlock.Text = gradePointAverage.ToString("0.00");
            TotalCreditTextBlock.Text = totalCredit.ToString();
        } 
        #endregion

        private void GradeDeleteButton_Tapped(object sender, TappedRoutedEventArgs e)
        {
            Button deleteButton = sender as Button;
            Grade gradeToDelete = deleteButton.DataContext as Grade;
            Debug.WriteLine("grade to delete : {0}", gradeToDelete.ToString());

            Grades.Remove(gradeToDelete);
            calculateGPA();
        }

        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            Grades = new ObservableCollection<Grade>();
            GradeListView.ItemsSource = Grades;
        }
    }
}
